from Gnuplot import Gnuplot

class Plotter:
    def __init__(self, pa):
        self.pa = pa
        self.correlations = {}
        self.plot = Gnuplot()

    def getCorrelations(self, baselines=range(7)):
        correlations = self.pa.correlations(baselines)
        for i in baselines:
            self.correlations[i] = correlations[i]

    def multiPlot(self,
                  plots,
                  setstyle='set style data linespoints'
                  ):
        dy = 1./len(plots)
        dys = "%.2f" % dy
        self.plot.reset()
        self.plot(setstyle)
        self.plot('set noxtic')
#        self.plot('set noytic')
        self.plot('set nokey')
        self.plot('set rmargin 0; set lmargin 0')
        self.plot('set tmargin 0; set bmargin 0')
        self.plot('set size 0.9,'+"%.2f"%dy)
        self.plot('set multiplot')
        for i in range(len(plots)):
            self.plot('set origin 0.05,'+"%.2f"%(dy*i))
            self.plot.plot(plots[i])
        self.plot('set nomultiplot')
        
    def plotCorrelations(self, baselines=range(7)):
        out = []
        for i in baselines:
            out.append(self.correlations[i])
        self.multiPlot(out)

if __name__ == "__main__":
    from sys import argv
    from optparse import OptionParser
    from time import sleep
    from rpyc import connect
    usage = "usage: %prog [options] arg"
    parser = OptionParser(usage)
    parser.add_option("-c",
                      "--host",
                      action = "store",
                      type = "string",
                      dest = "host",
                      default = "128.171.116.239")
    parser.add_option("-p",
                      "--port",
                      action = "store",
                      type = "int",
                      dest = "port",
                      default = 18861)
    parser.add_option("-i",
                      "--integration-time",
                      action = "store",
                      type = "int",
                      dest = "int_time",
                      default = 10)
    (options, args) = parser.parse_args()
    if options.host:
        host = options.host
    if options.port:
        port = options.port
    if options.int_time:
        int_time = options.int_time
    
    pa = connect(host,port)
    pap = Plotter(pa.root)
    print "Ctrl-C to stop..."
    try:
        while True:
            pa.root.getCorrelations(int_time)
            pap.getCorrelations()
            pap.plotCorrelations([1,2])
    except:
        print "Stopped."
